# import modbus_tk
import modbus_tk
import modbus_tk.defines as cst
import modbus_tk.modbus_tcp as modbus_tcp
import time
from constance import config


# ip是读取modbus的IP地址
# court_id是场地号，其中使用10000代表所有场地
# opt代表开灯、关灯、查询操作，分别用ON(1),OFF(0),query(11)来代表
def send_message(ip, court_id, opt, plc_total):
    # 连接MODBUS TCP从机
    master = modbus_tcp.TcpMaster(host=ip)
    master.set_timeout(5.0)
    # 获取状态
    id_opt = int(get_opt(opt))
    id_num = court_id - 1
    if court_id == 10000:
        if id_opt == 1:
            for i in range(0, plc_total):
                master.execute(1, cst.WRITE_SINGLE_REGISTER, i, output_value=1)
                time.sleep(1.5)
            return "SUCCESS", "ALL_ON"
        elif id_opt == 0:
            for i in range(0, plc_total):
                master.execute(1, cst.WRITE_SINGLE_REGISTER, i, output_value=0)
                time.sleep(1.5)
            return "SUCCESS", "ALL_OFF"
        elif id_opt == 11:
            all_res = master.execute(1, cst.READ_HOLDING_REGISTERS, 0, plc_total)
            return all_res  # get_all_results(all_res)
        else:
            return "FAIL", "ERROR"
    if id_opt == 11:
        # 读寄存器
        c_input = master.execute(1, cst.READ_HOLDING_REGISTERS, id_num, 1)
        return get_result(c_input)
    else:
        # 单个读写寄存器操作
        master.execute(1, cst.WRITE_SINGLE_REGISTER, id_num, output_value=id_opt)
        # 读寄存器
        res_result = master.execute(1, cst.READ_HOLDING_REGISTERS, id_num, 1)
        return get_result(res_result)


def get_all_results(res):
    getlist = list(res)
    for item in range(len(getlist)):
        if getlist[item] == 1:
            getlist[item] = 'ON'
        elif getlist[item] == 0:
            getlist[item] = 'OFF'
        else:
            getlist[item] = 'ERROR'
    return getlist


def get_result(court_id):
    if court_id[0] == 1:
        return "SUCCESS", "ON"
    elif court_id[0] == 0:
        return "SUCCESS", "OFF"
    else:
        return "FAIL", "ERROR"


def get_opt(opt):
    if opt == 'ON':
        return '1'
    elif opt == 'OFF':
        return '0'
    else:
        return '11'
    # opt == 'QUERY':
    # else:
    #     return 'ERROR'


if __name__ == "__main__":
    try:
        #         # res = send_message('192.168.1.16', 10000, 'ON')
        #         # print(res)
        #         #
        #         # res = send_message('192.168.1.16', 4, 'ON')
        #         # print(res)
        #         #
        #         # res = send_message('192.168.1.16', 4, 'OFF')
        #         # print(res)
        #
        res = send_message('10.100.9.9', 1, 'query', 21)
        print(res)
    #         # res = send_message('192.168.1.16', 4, 'OFF')
    #         # print(res)
    #
    except modbus_tk.modbus.ModbusError as e:
        print("%s- Code=%d" % (e, e.get_exception_code()))
